/*
Disclaimer of Warranty: THE PACKAGE IS PROVIDED
BY THE COPYRIGHT HOLDER AND CONTRIBUTORS "AS IS'
AND WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES.
THE IMPLIED WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT
ARE DISCLAIMED TO THE EXTENT PERMITTED BY YOUR LOCAL LAW.
UNLESS REQUIRED BY LAW, NO COPYRIGHT HOLDER OR
CONTRIBUTOR WILL BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
OR CONSEQUENTIAL DAMAGES ARISING IN ANY WAY OUT OF THE USE OF
THE PACKAGE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.


(c) Copyright 2013 Edward Principe
All Rights Reserved

*/
#include "parse.h"

///////////////////////////////////////////////////////////
// Next: Parses next word
///////////////////////////////////////////////////////////
SyntaxErr Parse::Next()
{
    // Locals
	bool is_first = true;

    // Erase word
	_word.erase(_word.begin(), _word.end());

    // Reset string flag
	_is_string = false;

    // Go thru white spaces
	while (*_i <= L' ')
	{
        // At end?
		if (_i == _buffer.end())
		{
			_is_end = true;
			return SE_NONE;
		}

        // Is it a comment?
		if (*_i == _com)
		{
			_is_end = true;
			return SE_NONE;
		}

        // Increment iterator
		_i++;
	}

    // Is it a string?
	if (*_i == L'"')
	{
		_is_string = true;
		_i++;
	}

    // Main parse loop
	while (true)
	{
		// At end?
		if (_i == _buffer.end())
		{
			_is_end = true;
			return _is_string ? SE_BAD_STRING : SE_NONE;
		}

		// A comment?
		if (!_is_string && *_i == _com)
		{
			_is_end = true;
			return SE_NONE;
		}

		// End of string character
		if (*_i == L'"')
		{
			_i++;
			return _is_string ? SE_NONE : SE_BAD_STRING;
		}

		// A white space?
		if (!_is_string && *_i <= L' ')
		{
			return SE_NONE;
		}

		// A deliminator?
		if (!_is_string)
		{
			// Iterate thru deliminators
			for (wstring::iterator d = _delim.begin(); d != _delim.end(); d++)
			{
				// Is it a deliminator?
				if (*d == *_i)
				{
					if (is_first)
					{
						_word += *_i;
						_i++;
					}

					return SE_NONE;
				}
			}
		}
        
		// Get word
		_word += *_i;
		is_first = false;
		_i++;
	}
}